package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.AddressBookPageQueryResDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageHelperUtils;
import com.jzo2o.mysql.utils.PageUtils;
import jodd.util.ArraysUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }



    /**
     * 新增地址簿
     * @param dto
     */
    @Override
    @Transactional
    public void addAddressBook(AddressBookUpsertReqDTO dto) {
        //1.判断dto是否为空，为空抛出错误信息
        if (BeanUtils.isEmpty(dto)){
            throw new BadRequestException("地址簿信息为空，添加失败");
        }
        //2.判断是否设置为了默认地址簿
        if (dto.getIsDefault().equals(CertificationStatusEnum.INIT.getStatus())){
            //2.1没设置的话直接存入数据库
            AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);
            addressBook.setUserId(UserContext.currentUserId());
            boolean save = this.save(addressBook);
            if (!save){
                throw new DBException("新增地址簿失败");
            }
            //3.判断是否操作成功
        }else {
            //2.3根据用户id去查询状态为默认地址簿的地址
            Integer count = this.lambdaQuery()
                    .eq(AddressBook::getIsDefault, CertificationStatusEnum.PROGRESSING.getStatus())
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .count();
            if (count>0){
                LambdaUpdateWrapper<AddressBook> updateWrapper = Wrappers.<AddressBook>lambdaUpdate()
                        .eq(AddressBook::getIsDefault, CertificationStatusEnum.PROGRESSING.getStatus())
                        .eq(AddressBook::getUserId,  UserContext.currentUserId())
                        .set(AddressBook::getIsDefault, CertificationStatusEnum.INIT.getStatus());
                boolean update = this.update(updateWrapper);
            }
            //2.2将默认地址簿的地址簿状态改为非默认，然后再插入该地址簿
            AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);
            addressBook.setUserId(UserContext.currentUserId());
            boolean save = this.save(addressBook);

            //3.判断是否操作成功
            if (!save){
                throw new BadRequestException("添加失败");
            }

        }
    }


    /**
     * 分页查询地址簿
     * @param dto
     * @return
     */
    @Override
    public AddressBookPageQueryResDTO getPage(AddressBookPageQueryReqDTO dto) {
        //根据用户id分页查询用户地址
        IPage<AddressBook> page=new Page<>(dto.getPageNo(),dto.getPageSize());
        this.lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .page(page);
        List<AddressBook> records = page.getRecords();
        List<AddressBookResDTO> list=new ArrayList<>();
        for (AddressBook record : records) {
            AddressBookResDTO addressBookResDTO = BeanUtils.copyBean(record, AddressBookResDTO.class);
            list.add(addressBookResDTO);
        }

        AddressBookPageQueryResDTO addressBookPageQueryResDTO = new AddressBookPageQueryResDTO();
        addressBookPageQueryResDTO.setList(list);
        addressBookPageQueryResDTO.setTotal(page.getTotal());
        addressBookPageQueryResDTO.setPages(page.getPages());
        return addressBookPageQueryResDTO;
    }


    /**
     * 查询地址簿详情
     * @param id
     * @return
     */
    @Override
    public AddressBookResDTO getAddressBook(Long id) {
        if (id==0){
            throw new  BadRequestException("id为空");
        }
        AddressBook addressBook = this.getById(id);
        if (BeanUtils.isEmpty(addressBook)){
            throw new BadRequestException("该地址簿不存在");
        }
        AddressBookResDTO addressBookResDTO = BeanUtils.copyBean(addressBook, AddressBookResDTO.class);
        return addressBookResDTO;
    }


    /**
     * 修改地址簿
     * @param id
     * @param dto
     */
    @Override
    public void updateAddressBook(Long id, AddressBookUpsertReqDTO dto) {
        //1.首先判断id是否为空
        if (id==null){
            throw new BadRequestException("id为空");
        }
        //2.判断对应id的地址簿是否存在
        AddressBook addressBook = this.getById(id);
        if (BeanUtils.isEmpty(addressBook)){
            throw new BadRequestException("对应id的地址簿不存在");
        }
        //3.修改
        AddressBook upAddressBook = BeanUtils.copyBean(dto, AddressBook.class);
        upAddressBook.setId(id);
        boolean result = this.saveOrUpdate(upAddressBook);
        //4.判断是否修改成功
        if (!result){
            throw new DBException("修改失败");
        }
    }

    /**
     * 设置默认地址簿
     * @param id
     * @param flag
     */
    @Override
    public void updateDefault(Long id, Integer flag) {
        //1.判断对应id的地址是否为空，为空结束
        AddressBook addressBook = this.getById(id);
        if (BeanUtils.isEmpty(addressBook)){
            throw new BadRequestException("对应的地址簿不存在");
        }
        //2.判断flag是否为1（代表设置默认）
        if (flag.equals(CertificationStatusEnum.PROGRESSING.getStatus())){
            //将对应id的地址簿修改为1，将其对应用户id的地址簿状态为1的改为0
            Integer count = this.lambdaQuery()
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .eq(AddressBook::getIsDefault, CertificationStatusEnum.PROGRESSING.getStatus())
                    .count();
            if (count>0){
                LambdaUpdateWrapper<AddressBook> updateWrapper = Wrappers.<AddressBook>lambdaUpdate()
                        .eq(AddressBook::getIsDefault, CertificationStatusEnum.PROGRESSING.getStatus())
                        .eq(AddressBook::getUserId,  UserContext.currentUserId())
                        .set(AddressBook::getIsDefault, CertificationStatusEnum.INIT.getStatus());
                boolean update = this.update(updateWrapper);
            }
            AddressBook addressBook1 = new AddressBook();
            addressBook1.setId(id);
            addressBook1.setIsDefault(flag);
            this.saveOrUpdate(addressBook1);
        }else {
            //3.为0的话直接修改即可
            AddressBook addressBook1 = new AddressBook();
            addressBook1.setId(id);
            addressBook1.setIsDefault(flag);
            this.saveOrUpdate(addressBook1);
        }
    }

    /**
     * 地址簿的批量删除
     * @param ids
     */
//    @Override
//    public void batch(String ids) {
//        //1.判断字符串是否为空串
////        List<Long> longIds = ids.stream()
////                .map(Long::parseLong)
////                .collect(Collectors.toList());
//
//    }


    @Override
    public void batch(List<String> ids) {
        if(ids==null){
            throw new BadRequestException("没有数据无法删除");
        }        //将字符串类型的数据转换为Long类型的集合
        List<Long> longIds = ids.stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());
        boolean result = this.removeByIds(longIds);
        if (!result){
            throw new DBException("删除失败");
        }
    }
}
